using XjjXmm.Infrastructure.ToolKit;

namespace xjjxmm.infrastructure.Middleware.RateLimit;

public class RateLimitModel : IDisposable
{
    /// <summary>
    /// 最大令牌数量
    /// </summary>
    private int maxPermits;

    /// <summary>
    /// 每秒新增令牌数量
    /// </summary>
    private int addPermitRate;

    /// <summary>
    /// 备用令牌数量
    /// </summary>
    // private int backupPermitRate;

    /// <summary>
    /// 当前令牌数量
    /// </summary>
    private int currentPermis;

    /// <summary>
    /// 临时后备令牌数量
    /// </summary>
    // private int currentBackupPermitRate;

    //1.创建取消令牌数据
    //private CancellationTokenSource tokenSource;
    //2.创建取消令牌
    // CancellationToken token;

    private long startTime;

    private long endTime;

    public RateLimitModel(int permitRate, int maxPermits)
    {
        addPermitRate = permitRate;
        this.maxPermits = maxPermits;
        //this.backupPermitRate = backupPermitRate;

        currentPermis = maxPermits;
        //   currentBackupPermitRate = backupPermitRate;

        // tokenSource = new CancellationTokenSource();
        // token = tokenSource.Token;

        //AddPermit();

        startTime = DateTime.Now.ToTotalMilliseconds();
    }


    /// <summary>
    /// 添加令牌
    /// </summary>
    private void AddPermit()
    {
        endTime = DateTime.Now.ToTotalMilliseconds();
        int ticket = (int)(endTime - startTime) / 1000;
        currentPermis += ticket * addPermitRate;

        if (currentPermis >= maxPermits)
        {
            currentPermis = maxPermits;
            //currentBackupPermitRate = backupPermitRate;
        }

        startTime = DateTime.Now.ToTotalMilliseconds();
        /*while (!token.IsCancellationRequested)
        {
            currentPermis += addPermitRate;
            if (currentPermis >= maxPermits)
            {
                currentPermis = maxPermits;
                currentBackupPermitRate = backupPermitRate;
            }

            await Task.Delay(1000, token);
        }*/

    }

    public bool Acquire()
    {
        AddPermit();

        if (currentPermis > 0)
        {
            currentPermis--;
            return true;
        }



        return false;
    }


    public void Dispose()
    {
        //  tokenSource.Cancel();
        // tokenSource.Dispose();
    }
}